import classNames from 'classnames'
import './index.css'
import { useState } from 'react'
import { produce } from 'immer'

function HelloWorld({ name }) {
  // useState此hook用来实现函数组件内部的状态，状态(state)驱动视图（UI）, UI = f(state)
  let [count, setCount] = useState(1)
  let [userInfo, setUserInfo] = useState({ name: '汪哥', age: 18 })
  let [teacher, setTeacher] = useState([
    { id: 1, name: '汪老师' },
    { id: 2, name: '胡老师' },
  ])

  // 组合多个类名
  let classnames = classNames('username', 'abc', 'def', { xyz: false })

  const updateCount = () => {
    // setCount(count + 1)
    // setCount(count + 1)
    // setCount(count + 1) // 仅最后一次生效

    setCount((preCount) => {
      return preCount + 1
    })
    setCount((preCount) => {
      return preCount + 1
    })
    setCount((preCount) => {
      return preCount + 1
    })
  }

  const btnClickHandle = () => {
    setCount(100)
  }

  const countAdd = () => {
    setCount((count) => {
      count += 1
      return count
    })
  }

  const updUserInfo = () => {
    // state特点：不可变。不可以改变原对象，需要设置一个新的内存地址对象。才可以驱动页面更新
    // userInfo.name = '谭逸轩'
    // setUserInfo(userInfo) // 不行 ，页面不会更新

    // 设置一个新对象（新内存）
    // setUserInfo({ name: '程泉峰', age: 19,a:{b:c{}} }) // ok  页面会更新
    let newUserInfo = { ...userInfo } // 浅拷贝(对象若仅有一层，相当于浅拷贝相当于深拷贝)
    // console.log(newUserInfo === userInfo) // false
    newUserInfo.name = '程泉峰'
    setUserInfo(newUserInfo)
  }

  const addTeacher = () => {
    let newTeacher = [{ id: Date.now(), name: '陶老师' }, ...teacher]
    setTeacher(newTeacher)
  }

  const updUserInfo2 = () => {
    setUserInfo(
      produce((draft) => {
        draft.name = '林家福'
      })
    )
  }

  const addTeacher2 = () => {
    setTeacher(
      produce((draft) => {
        draft.push({ id: Date.now(), name: '陶老师' })
      })
    )
  }

  return (
    <>
      <ul>
        {teacher.map((teacher) => (
          <li key={teacher.id}>{teacher.name}</li>
        ))}
      </ul>
      <button onClick={addTeacher}>添加一个老师</button>
      <button onClick={addTeacher2}>添加一个老师2</button>
      <h1>
        {userInfo.name},{userInfo.age}
      </h1>
      <div>
        <button onClick={updUserInfo}>改对象信息1</button>
        <button onClick={updUserInfo2}>改对象信息2</button>
      </div>
      <h1 className={classnames}>你好，{name}</h1>
      <div>count:{count}</div>
      <button onClick={btnClickHandle}>改100</button>
      <button onClick={countAdd}>count++</button>
      <button onClick={updateCount}>setState函数式更新</button>
    </>
  )
}

export default HelloWorld
